package eggcatcher;

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import javax.imageio.ImageIO;

public class Chick extends TimerTask {
	private int pos_x;
	private int pos_y;
	private Image m;
	// public boolean isBreak;
	private ArrayList<Item> item;
	public Timer timer;
	private BufferedImage eggs,shits;
	private Image EggResizedImage,ShitResizedImage;
	public Thread thread;
	private static int sp=4;
	
	// private Shit shit;

	Chick(int posX, int posY, ArrayList<Item> t, Image u) {
		pos_x = posX;
		pos_y = posY;
		m = u;
		item = t;
		timer = new Timer();
		timer.scheduleAtFixedRate(this, 0, 5000L);
		
		//Toolkit toolkit = Toolkit.getDefaultToolkit();
		try {
			eggs = ImageIO.read(getClass().getResourceAsStream("egg.png"));
			shits = ImageIO.read(getClass().getResourceAsStream("shit.png"));
			EggResizedImage = eggs.getScaledInstance(eggs.getWidth()/4, eggs.getHeight()/4, Image.SCALE_FAST);
			ShitResizedImage = shits.getScaledInstance(shits.getWidth()/4, shits.getHeight()/4, Image.SCALE_FAST);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		
		thread = new Thread(new Runnable(){

			@Override
			public void run() {
				synchronized (this) {
					boolean flag=false;
					while (EggCatchAdvanced.gamesStart) {
							int dimen = pos_x;
							if (!flag) {
								dimen += 10;
								if (dimen >= 400)
									flag = true;
							}
							if (flag) {
								dimen -= 10;
								if (dimen <= 50)
									flag = false;
							}
							pos_x=dimen;

						
						try {
							Thread.sleep(100);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}
				
			
				
		});
		thread.start();
	}
	

	public void setItem(ArrayList<Item> t) {
		item = t;
	}

	public int getPosX() {
		return pos_x;
	}
	public void setPosX(int x) {
		pos_x = x;
	}

	public int getPosY() {
		return pos_y;
	}

	public Image getImage() {
		return m;
	}

	public void addItem(Item item) {
		this.item.add(item);
	}

	public ArrayList<Item> getItem() {
		return item;
	}

	public void clearItemList() {
		int k;
		for (k = 0; k < item.size(); k++) {
			if (item.get(k).notFalling())
				item.remove(k);
		}

	}

	@Override
	public void run() {
		int basketSize = EggCatchAdvanced.baskets.getEggsList().size();
		if (basketSize>0 && basketSize%20==0)
			sp+=2;
		Item t;
		int rand = (int) (Math.random()*10);
		if (rand<7) {
			t = new Egg(this.getPosX() + 20, 100, sp, EggResizedImage);			
		}
		else 
			t = new Shit(this.getPosX() + 20, 100, sp, ShitResizedImage);
			item.add(t);
		
		
	}

}
